﻿using System;
using System.Data;

namespace DotNet.Extention
{
    /// <summary>
    /// 数据访问相关扩展方法
    /// </summary>
    public static class DataExtention
    {
        /// <summary>
        /// 从Datareader读取指定列的值，并转换成字符串
        /// </summary>
        /// <param name="rdr">IDataReader</param>
        /// <param name="index">列索引</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static string GetString(this IDataReader rdr, int index, string defaultValue)
        {
            if (rdr.GetValue(index) == DBNull.Value)
                return defaultValue;
            return Convert.ToString(rdr.GetValue(index));
        }

        /// <summary>
        /// 从Datareader读取指定列的值，并转换成时间
        /// </summary>
        /// <param name="rdr">IDataReader</param>
        /// <param name="index">列索引</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static DateTime? GetDateTime(this IDataReader rdr, int index, DateTime? defaultValue)
        {
            if (rdr.GetValue(index) == DBNull.Value)
            {
                return defaultValue;
            }
            return Convert.ToDateTime(rdr[index]);
        }

        /// <summary>
        /// 从Datareader读取指定列的值，并转换成整数
        /// </summary>
        /// <param name="rdr">IDataReader</param>
        /// <param name="index">列索引</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static int GetInt(this IDataReader rdr, int index, int defaultValue)
        {
            if (rdr.GetValue(index) == DBNull.Value)
            {
                return defaultValue;
            }
            return Convert.ToInt32(rdr[index]);
        }


        /// <summary>
        /// 将指定的Object转换成整型值
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static int ToInt(this object obj)
        {
            return Convert.ToInt32(obj);
        }

        /// <summary>
        /// 将指定的Object转换成布尔型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool ToBoolean(this object obj)
        {
            return Convert.ToBoolean(obj);
        }

        /// <summary>
        /// 获取DataSet中默认的DataTable
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static DataTable GetDefaultDataTable(this DataSet ds)
        {
            if (ds.Tables.Count >= 1)
                return ds.Tables[0];
            return null;
        }
    }
}
